import React, { Component, useState, useEffect } from "react";
import { Table, Input, InputNumber, Popconfirm, Form, message, Button, Select, Space, ConfigProvider } from 'antd';
// import from './index.css';
import { Axios } from 'toolkit';
import zhCN from 'antd/es/locale/zh_CN';  // 引入中文包
import { PlusCircleTwoTone, SearchOutlined } from '@ant-design/icons';
import Item from 'antd/lib/list/Item';
const { Option } = Select;

interface Item {
  id: string;
  code: string;
  name: string;
  createTime: string;
  updateTime: string;
  operation: string;
}

interface Result {
  message: string,
  succeed: boolean,
  data: Page
}

interface Page {
  "toatlePage": number,
  "toatleCount": number,
  "pageSize": number,
  "values": Item[]
}

interface EditableCellProps extends React.HTMLAttributes<HTMLElement> {
  editing: boolean;
  dataIndex: string;
  title: any;
  inputType: 'number' | 'text';
  record: Item;
  index: number;
  children: React.ReactNode;
}

const _getInputNode = (inputType:string) =>{
  if(inputType === 'number') {
    return <InputNumber />;
  }
  if(inputType === 'select') {
   return (<Select
    placeholder="请选择"
    optionFilterProp="children"
    onChange={() =>{}}
    onFocus={() =>{}}
    onBlur={() =>{}}
  >
    <Option value="jack">jack</Option>
    <Option value="lucy">lucy</Option>
    <Option value="tom">tom</Option>
  </Select>);
  }
  return <Input />;
}

const EditableCell: React.FC<EditableCellProps> = ({
  editing,
  dataIndex,
  title,
  inputType,
  record,
  index,
  children,
  ...restProps
}) => {
  const inputNode = _getInputNode(inputType);
  
  return (
    <td {...restProps}>
      {editing ? (
        <Form.Item
          name={dataIndex}
          style={{ margin: 0 }}
          rules={[
            {
              required: true,
              message: `请输入${title}!`,
            },
          ]}
        >
          {inputNode}
        </Form.Item>
      ) : (
          children
        )}
    </td>
  );
};

const AreaPage = () => {
  const searchRef = React.useRef<any>();
  const [form] = Form.useForm();
  const [data, setData] = useState<Item[]>();
  const [page, setPage] = useState<number>(0);
  const [total, setTotal] = useState<number>(0);
  const [editingKey, setEditingKey] = useState('');
  const [searchValue, setSearchValue] = useState('');
  const pageSize: number = 5;

  const isEditing = (record: Item) => record.id === editingKey; 

  const edit = (record: Item) => {
    form.setFieldsValue({ ...record });
    setEditingKey(record.id);
  };

  const cancel =() => {
    setEditingKey('');
    if (editingKey === 'add') {
      let newData: any = [...data];
      newData.splice(0, 1);
      setData(newData)
    }
  }



  useEffect(() => {
    query();

    return () => { }
  }, [page,searchValue])

  const query = () => {
    Axios.post(`/districtList?conditionText=${searchValue}`, {
      limit: pageSize,
      pageNum: page,
    }).then(res => {
      // setPage(res.data.data)
      let reslut: Result = res.data;
      if (!reslut.succeed) {
        message.error(reslut.message);
        return;
      }
      let resultData = reslut.data.values.map((item: Item, index: number) => {
        return {
          ...item, index: index + 1
        }
      })
      setData(resultData);
      setTotal(reslut.data.toatleCount);
      // console.log(page)

    }).catch(error => {
      console.error(error);
      message.error(error.message);
    })
  }

  React.useEffect(() => {
    Axios.post('/sysEnumList', {}, { headers: { DISTRICT_CODE: 1111 } }).then((res: any) => {
      console.log(res)
    }).catch((error) => { })
  }, [])

  // 点击 新增 出现输入框
  const openAdd = async (): Promise<void> => {
    try {
      if (editingKey !== '') {
        message.error('请先保存');
        return;
      }
      const row: any = {
        id: 'add', // 这里也是 add
        code: '',
        name: '',
        status: 0,
        createTime: '',
        updateTime: '',
        operation: '',
      };
      const newData = [...data];
      newData.unshift(row)
      setData(newData);
      setEditingKey('add');
      form.resetFields();//保存后清空表单内容

    } catch (errInfo) {
    }
  };


  // 编辑 和 新增
  const save = async (id: string) => {
    const row = (await form.validateFields()) as Item;
    const newData = [...data];
    const index = newData.findIndex(item => id === item.id);
    let params: any = {
      ...newData[index],
      ...row
    }
    if (id !== 'add') {
      Axios.post('/updateDistrict', params).then((res: any) => {
        if (res.data.succeed) {
          message.success('编辑成功');
          newData.splice(index, 1, params);
          setData(newData);
          setEditingKey('');
        } else {
          message.error(res.data.message)
        }
      }).catch((error) => {

      })
    } else {
      delete params.id;
      Axios.post('/addDistrict', params).then((res: any) => {
        if (res.data.succeed) {
          message.success('新增成功');
          newData.splice(index, 1, params);
          setData(newData);
          setEditingKey('');
          query();
        } else {
          message.error(res.data.message)
        }
      }).catch((error) => {

      })
    }

  };


  const del = async (id: string) => {
    try {
      const res = await Axios.post('/removeDistrict', { "id": id })
      let result = res.data

      if (result.succeed == true) {
        const newData = [...data];
        const index = newData.findIndex((item) => id === item.id);
        newData.splice(index, 1);
        query();
        setData(newData);
        setEditingKey('');
      } else {

        message.error(result.message);
      }
    } catch (error) {
      console.error(error);
    }

  };

  const columns = [
    { title: '行号', dataIndex: 'index', width: '5%', 
      render: (text, record: TableItem, index) => {
      let rowNum = page * pageSize  + index + 1;
      return (<div>{rowNum}</div>)
  }
    },
    { title: '机构编码', dataIndex: 'code', width: '10%', editable: true },
    { title: '机构名称', dataIndex: 'name', width: '10%', editable: true },
    { title: '创建时间', dataIndex: 'createTime', width: '15%', },
    { title: '更新时间', dataIndex: 'updateTime', width: '15%', },
    {
      title: '操作', dataIndex: 'operation', width: '8%',
      // 点击新增  editable  为true
      render: (_: any, record: Item) => {
        const editable = isEditing(record);
        return editable ? (
          <span>
            <a href="javascript:;" onClick={() => save(record.id)} style={{ marginRight: 8 }}>
              保存
            </a>
            <a onClick={cancel}>取消</a>
          </span>
        ) : (
            <Space>
            
              <a disabled={editingKey !== ''} onClick={() => edit(record)}>
                编辑
            </a>
              <Popconfirm title="确认删除吗？" onConfirm={() => del(record.id)} okText="确定" cancelText="取消">
                <a>删除</a>
              </Popconfirm>

            </Space>
          );
      },
    },
  ];

const _getInputType = React.useCallback((dataIndex:string) =>{
  // if(dataIndex === 'agdistrictIde') {
  //   return 'number';
  // }
  if(dataIndex === 'districtId') {
    return 'select';
  }
},[])

  const mergedColumns = columns.map(col => {
    if (!col.editable) {
      return col;
    }
    return {
      ...col,
      onCell: (record: Item) => ({
        record,
        // 在这控制
        inputType: _getInputType(col.dataIndex),
        dataIndex: col.dataIndex,
        title: col.title,
        editing: isEditing(record),
      }),
    };
  });

  return (
    <ConfigProvider locale={zhCN}>
      <div>
        <Space className="div-search" style={{ margin: '20px 0' }}>
          <Input
            style={{ width: '300px' }}
            
            ref={searchRef}
            placeholder="请输入区域编码或区域名称快速筛选"
          />

          {/* 变量拿到值 */}
          <Button type="primary" icon={<SearchOutlined />} onClick={() =>{
            setSearchValue(searchRef.current.state.value)
          }}>
            搜索
          </Button>
        </Space >
        <div className="div-add">
          <Button type="primary" onClick={() => openAdd()} icon={<PlusCircleTwoTone />} style={{ marginBottom: '10px' }}>
            新建
          </Button>
        </div>
        <Form form={form} component={false}>
          <Table rowKey={(recode) => recode.id}
            style={{
              overflow: 'hidden',
              whiteSpace: 'nowrap',
              textOverflow: 'ellipsis',
              cursor: 'pointer'
            }}
            size="middle"
            components={{
              body: {
                cell: EditableCell,
              },
            }}
            dataSource={data}
            columns={mergedColumns}
            rowClassName="editable-row"
            pagination={{
              showTotal: function showTotal(total) {
                return `总共 ${total} 条`;
              },
              pageSize: pageSize,
              onChange: (page, pageSize) => {
                setPage(page - 1);
              },
              showQuickJumper:true,
              total: total
              // pageSize: data.pageSize,
              // total: data.toatleCount

            }}
          />
        </Form>
      </div>
    </ConfigProvider>
  );
};


export default AreaPage;